import React, { useState, useEffect } from "react";
import {
  Card,
  Button,
  Table,
  Tag,
  message,
  Modal,
  Form,
  Select,
  Statistic,
} from "antd";
import axios from "axios";
import { getAuthToken } from "@/router"; // 确保这个函数能获取有效的 JWT token

// 折扣档位与消耗魔力值映射
const DISCOUNT_OPTIONS = [
  { label: "5折（消耗1000魔力值）", value: 5, cost: 1000 },
  { label: "6折（消耗1000魔力值）", value: 6, cost: 1000 },
  { label: "7折（消耗1000魔力值）", value: 7, cost: 1000 },
  { label: "8折（消耗1000魔力值）", value: 8, cost: 1000 },
  { label: "9折（消耗1000魔力值）", value: 9, cost: 1000 },
];

function formatDate(dateStr) {
  if (!dateStr) return "-";
  const d = new Date(dateStr);
  return d.toLocaleDateString();
}

export default function DiscountCoupons() {
  const [coupons, setCoupons] = useState([]);
  const [userMagic, setUserMagic] = useState(0); // 用户魔力值
  const [loading, setLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [selectedDiscount, setSelectedDiscount] = useState(null);

  const columns = [
    {
      title: "折扣",
      dataIndex: "discountRate",
      key: "discountRate",
      render: (rate) => <Tag color="blue">{Math.round(rate * 10)}折</Tag>,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (s) => (
          <Tag color={s === "active" ? "green" : "default"}>
            {s === "active" ? "未使用" : "已使用"}
          </Tag>
      ),
    },
    {
      title: "有效期",
      dataIndex: "expiredAt",
      key: "expiredAt",
      render: (t) => formatDate(t),
    },
    {
      title: "获得时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (t) => formatDate(t),
    },
  ];

  // 创建带认证头的 axios 实例
  const createAuthHeaders = () => {
    const token = getAuthToken();
    return {
      headers: {
        Authorization: token ? `${token}` : "",
        "Content-Type": "application/json"
      },
    };
  };

  // 获取用户折扣券列表
  const fetchUserDiscountCoupons = async () => {
    try {
      setLoading(true);
      const response = await axios.get(
          "http://192.168.55.192:8080/api/promotion/my-discount-coupons",
          createAuthHeaders()
      );

      // 根据后端响应结构，数据在 response.data.data 中
      if (response.data && response.data.code === 200) {
        setCoupons(response.data.data || []);
      } else {
        message.error("获取折扣券失败: " + (response.data.message || "未知错误"));
      }
    } catch (error) {
      const errorMsg = error.response?.data?.message || error.message;
      message.error("获取折扣券失败: " + errorMsg);
    } finally {
      setLoading(false);
    }
  };

  // 获取用户魔力值 - 使用用户信息接口
  const fetchUserMagic = async () => {
    try {
      // 调用用户信息接口
      const response = await axios.get(
          "http://192.168.55.192:8080/api/user/info",
          createAuthHeaders()
      );

      // 根据用户信息接口响应结构
      if (response.data && response.data.code === 200) {
        // 从用户信息中提取魔力值
        setUserMagic(response.data.data?.magicValue || 0);
      } else {
        message.error("获取用户信息失败: " + (response.data.message || "未知错误"));
      }
    } catch (error) {
      const errorMsg = error.response?.data?.message || error.message;
      message.error("获取用户信息失败: " + errorMsg);
    }
  };

  // 兑换折扣券
  const exchangeDiscountCoupon = async (discountLevel) => {
    try {
      setLoading(true);
      const response = await axios.post(
          "http://192.168.55.192:8080/api/promotion/exchange-discount",
          { discountLevel }, // 请求参数名称改为 discountLevel
          createAuthHeaders()
      );

      if (response.data && response.data.code === 200) {
        message.success("兑换成功");
        return true;
      } else {
        message.error("兑换失败: " + (response.data.message || "未知错误"));
        return false;
      }
    } catch (error) {
      const errorMsg = error.response?.data?.message || error.message;
      message.error(`兑换失败: ${errorMsg}`);
      return false;
    } finally {
      setLoading(false);
    }
  };

  const handleExchange = () => {
    setModalOpen(true);
  };

  const handleModalOk = () => {
    form.validateFields().then(async (values) => {
      const discountLevel = values.discount; // 注意：这里 discount 对应的是选项的 value，即折扣等级（整数）
      const success = await exchangeDiscountCoupon(discountLevel);

      if (success) {
        setModalOpen(false);
        form.resetFields();
        setSelectedDiscount(null);
        // 重新获取折扣券和用户魔力值
        await Promise.all([fetchUserDiscountCoupons(), fetchUserMagic()]);
      }
    });
  };

  const handleModalCancel = () => {
    setModalOpen(false);
    form.resetFields();
    setSelectedDiscount(null);
  };

  useEffect(() => {
    // 初始化加载数据
    const loadData = async () => {
      setLoading(true);
      try {
        await Promise.all([fetchUserDiscountCoupons(), fetchUserMagic()]);
      } catch (error) {
        console.error("初始化加载失败", error);
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, []);

  return (
      <div style={{ padding: 24 }}>
        <div style={{ marginBottom: 16 }}>
          <Statistic
              title="当前魔力值"
              value={userMagic}
              suffix="点"
              valueStyle={{ color: "#1890ff", fontWeight: 600 }}
          />
        </div>
        <Card
            title="下载折扣券"
            extra={
              <Button type="primary" onClick={handleExchange}>
                兑换新折扣券
              </Button>
            }
            style={{ marginBottom: 24 }}
        >
          <p>可用魔力值兑换下载折扣券，下载资源时可抵扣部分魔力值。</p>
        </Card>
        <Card title="我的折扣券" loading={loading}>
          <Table
              columns={columns}
              dataSource={coupons}
              rowKey="id"
              pagination={false}
              loading={loading}
              locale={{ emptyText: "暂无可用折扣券" }}
          />
        </Card>
        <Modal
            title="兑换下载折扣券"
            open={modalOpen}
            onOk={handleModalOk}
            onCancel={handleModalCancel}
            okText="确定兑换"
            cancelText="取消"
            confirmLoading={loading}
            destroyOnClose
        >
          <Form form={form} layout="vertical">
            <Form.Item
                name="discount"
                label="选择折扣档位"
                rules={[{ required: true, message: "请选择折扣档位" }]}
            >
              <Select
                  placeholder="请选择折扣档位"
                  onChange={(v) => setSelectedDiscount(v)}
              >
                {DISCOUNT_OPTIONS.map((opt) => (
                    <Select.Option
                        key={opt.value}
                        value={opt.value}
                        disabled={userMagic < opt.cost}
                    >
                      {opt.label}
                      {userMagic < opt.cost && "（魔力值不足）"}
                    </Select.Option>
                ))}
              </Select>
            </Form.Item>
            {selectedDiscount && (
                <div style={{ marginTop: 8, color: "#888" }}>
                  兑换该折扣券将消耗
                  <span
                      style={{ color: "#faad14", fontWeight: 500, margin: "0 4px" }}
                  >
                {
                  DISCOUNT_OPTIONS.find((opt) => opt.value === selectedDiscount)
                      ?.cost
                }
              </span>
                  魔力值
                </div>
            )}
          </Form>
        </Modal>
      </div>
  );
}